import fetch from '@system.fetch'
// banner广告
import { getBannerNativeAd } from './banner_sdk.js'
// bqt广告
import { initBqtSdk, getBqtAd } from './bqt_sdk.js'
let ad_sdk_global = null
let global_data = {
  advIdsConfig: [], // 广告id集合
  nativeAdvIdsConfig: null, // 当前正在请求的广告位数据
  request_timeout: 2000, // 请求超时时间
}
const initNativeSdk = () => {
  ad_sdk_global = AD_SDK.ad_sdk_global
  if (ad_sdk_global.nativeAdData.length > 0) {
    global_data.advIdsConfig = []
    console.log(ad_sdk_global.nativeAdData, 'advIdsConfig______nativeAdData')
    global_data.request_timeout = ad_sdk_global.adNewPostionConfig.request_timeout || 2000
    ad_sdk_global.nativeAdData.forEach(item => {
      console.log(item, 'advIdsConfig______item')
      item.requestNum = 0 // 当前广告源广告请求顺序
      item.preloadTimer = null // 广告源预加载超时任务
      item.first_time_interval = item.first_time_interval || 0
      if (item.falls_switch) {
        let advIds = AD_SDK.computeAdvIdArr(item.ad_source, true, Number(item.time_num_fail))
        item.advIds = advIds
        item.previous_layers = Number(item.previous_layers || 0)
      }
      if (item.bidding_switch) {
        let advIds = AD_SDK.computeAdvIdArr(item.ad_bidding, true, Number(item.time_num_fail))
        item.biddingIds = advIds
      }
      global_data.advIdsConfig.push(item)
    });
    console.log(global_data.advIdsConfig, 'advIdsConfig______native')
  }
  ad_sdk_global.showTimers = {}
  ad_sdk_global.responseList = []
}
// 频控ID间隔控制
const sleepDelay = (time) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}
/**
 * 获取同层未频控id
 * @params nextLayer: 梯度
 * @params nextLayerObj: 当前层级数据
 * @params obj: 请求源参数
 */
const getPeerId = async (nextLayer, nextLayerObj, obj) => {
  let nextAdId = ''
  let advIdsConfig = global_data.advIdsConfig[obj.indexBoost]
  for (let i = nextLayerObj.curIndex; i < nextLayerObj.adsArr.length; i++) {
    if (nextLayerObj.adsArr[i].failNum < advIdsConfig.num_fail) {
      nextAdId = nextLayerObj.adsArr[i].id
      break
    } else {
      if (i >= nextLayerObj.adsArr.length - 1) {
        await sleepDelay(nextLayerObj.time);
      }
      advIdsConfig.requestNum++
      let param = {
        id: nextLayerObj.adsArr[i].id,
        ad_network: advIdsConfig.ad_type == 1 ? 1 : 18,
        ad_type: nextLayerObj.type == 'ylh' ? '优量汇' : nextLayerObj.type == 'renderer' ? '原生2.0' : '原生模板',
        scenario: advIdsConfig.name,
        popGroupName: obj.popGroupName,
        popName: obj.popName,
        requestNum: advIdsConfig.requestNum,
        adTurn: obj.requestNum,
        result: '广告频控',
        layer: nextLayer,
        scene: obj.scene
      }
      console.log(param, '触发频控')
      AD_SDK.uploadAdInfo('control', param)
    }
  }
  return nextAdId
}
/**
 * 获取梯度
 * @decs 自渲染、模板混用，补量需判断广告类型
 */
const getNextLayer = (obj, cur_config) => {
  let nextLayer = cur_config.curLayer
  const isNative = cur_config.layers.some(v => v.type == 'renderer'),
    isCustom = cur_config.layers.some(v => v.type != 'renderer')
  // 自渲染、模板混用且补量状态
  if (!obj.isBidding && isNative && isCustom && obj.scene.indexOf('补量') != -1) {
    const nextLayerObj = cur_config.layers[nextLayer],
      adPool = TACTICS_SDK.getGlobalData('ad_pool'),
      status = adPool.status == 1,
      custom_status = adPool.custom_status == 1
    // 当前广告类型和补量类型不匹配，需跳过当前梯度
    if ((status && !custom_status && nextLayerObj.type != 'renderer') || (custom_status && !status && nextLayerObj.type == 'renderer')) {
      cur_config.curLayer++
      nextLayer = cur_config.curLayer
    }
  }
  return nextLayer
}
/**
 * 获取下一个广告位数据
 * @returns {Object} 广告位数据{id:广告位id,layer:层级}
 */
async function getNextAdId(obj, isFirstLoad = false) {
  let advIdsConfig = global_data.advIdsConfig[obj.indexBoost]
  if (!advIdsConfig) {
    return
  }
  // 更新广告源广告id数据
  global_data.nativeAdvIdsConfig = advIdsConfig[`${obj.isBidding ? 'biddingIds' : 'advIds'}`]
  // 当前层级
  let currentLayer = 0
  if (isFirstLoad) {
    // 前几层开始请求
    if (obj.requestNum == 1 && Number(advIdsConfig.first_layers) > 0) {
      //首轮从哪一层开始
      currentLayer = advIdsConfig.first_layers >= global_data.nativeAdvIdsConfig.maxLayer ? global_data.nativeAdvIdsConfig.maxLayer - 1 : advIdsConfig.first_layers - 1
    } else if (!obj.isBidding && Number(advIdsConfig.previous_layers) > 0) {
      // 后续成功后从哪一层开始
      const previousLayers = global_data.nativeAdvIdsConfig.yetLayer - advIdsConfig.previous_layers
      currentLayer = previousLayers > 0 ? previousLayers : 0
    }
  } else {
    currentLayer = global_data.nativeAdvIdsConfig.curLayer
  }

  global_data.nativeAdvIdsConfig.curLayer = currentLayer
  let cur_config = global_data.nativeAdvIdsConfig
  let nextAdId = '',
    nextLayer = 0, // 梯度
    styleType = '', // 广告类型
    ecpm = 0,
    curIndex = 0, // 当前梯度的广告位顺序
    time = 0, // 当前层级请求间隔时间
    target_price = 0, // bidding目标过滤价
    current_status = 1 // 当前广告位点击率状态

  // 当前层级已达到最底层 则返回空id

  if (cur_config.curLayer + 1 <= cur_config.maxLayer) {
    // 上一个广告位的点击控制状态，如果被控制就拿它的下一层级发起新的请求
    if (obj.preDeleteStatus.stauts) {
      cur_config.curLayer = ++obj.preDeleteStatus.layer
    }

    nextLayer = getNextLayer(obj, cur_config)
    let nextLayerObj = cur_config.layers[nextLayer]

    // 同层级没有可用id，取下一层级
    if (obj.preDeleteStatus.stauts && !nextLayerObj) {
      obj.preDeleteStatus.stauts = false
      let nextObj = await getNextAdId(obj, true)
      return nextObj
    }
    curIndex = nextLayerObj.curIndex
    if (advIdsConfig.num_fail > 0) {
      nextAdId = await getPeerId(nextLayer, nextLayerObj, obj)
      if (!nextAdId) {
        // 同层级没有可用id，取下一层级
        cur_config.curLayer++
        cur_config.layers[nextLayer]['curIndex'] =
          (nextLayerObj.curIndex + 1) % nextLayerObj.maxIndex
        let nextObj = await getNextAdId(obj, false)
        return nextObj
      }
    } else {
      nextAdId = nextLayerObj.adsArr[nextLayerObj.curIndex].id
    }
    styleType = nextLayerObj.type
    ecpm = nextLayerObj.ecpm
    time = nextLayerObj.time
    current_status = nextLayerObj.adsArr[nextLayerObj.curIndex].current_status
    target_price = nextLayerObj.target_price
    cur_config.curLayer++
    cur_config.layers[nextLayer]['curIndex'] = (nextLayerObj.curIndex + 1) % nextLayerObj.maxIndex
  }
  return {
    id: nextAdId,
    layer: nextLayer,
    styleType,
    ecpm,
    curIndex,
    time,
    target_price,
    current_status
  }
}
/**
 * 请求原生广告
 * @param scenario 触发场景
 * @param sceneCode 触发场景
 * @param callback 广告获取完成后的回调
 */
async function getNewNativeAdv(obj, callback, isFirstLoad = true) {
  LOG('AD', 'getNewNativeAdv', obj)
  let { scenario, sceneCode, adType, adTimes, popName, popGroupName, requestNum, indexBoost, scene, isBidding, index, adTypes } = obj
  //取一个广告位数据
  let nativeAdvConfig = await getNextAdId(obj, isFirstLoad)
  LOG('AD', 'getNextAdId==>', requestNum, nativeAdvConfig)
  let advIdsConfig = global_data.advIdsConfig[indexBoost]
  if (nativeAdvConfig.id) {
    scenario = advIdsConfig.name
    advIdsConfig.requestNum++
    let param = {
      id: nativeAdvConfig.id,
      layer: nativeAdvConfig.layer,
      ad_network: 1,
      scenario,
      type: 'manu_ad',
      popName,
      popGroupName,
      requestNum: advIdsConfig.requestNum,
      scene,
      adTurn: requestNum,
      ad_type: '原生2.0',
      result: '发起请求',
      indexBoost,
      index,
      adTypes
    }
    let preloadTimer = advIdsConfig.preloadTimer
    let intervalTimer = null
    // 首轮是否应用层级请求间隔
    const timeout = (requestNum == 1 && !Boolean(advIdsConfig.first_time_interval)) ? 0 : nativeAdvConfig.time
    //获取广告数据
    let results = await new Promise((resolve, reject) => {
      intervalTimer = setTimeout(() => {
        preloadTimer = setTimeout(async () => {
          param.result = `无广告-超时未响应`
          resolve(false)
        }, global_data.request_timeout || 2000);
        const brand = ad_sdk_global.deviceInfo.brand,
          pvc = ad_sdk_global.deviceInfo.platformVersionCode,
          AD = require('@service.ad')
        if (nativeAdvConfig.styleType == 'ylh' && pvc >= 1100) {
          // 优量会广告区域
          param.ad_network = 18
          param.type = 'ylh'
          param.ad_type = '优量汇'
          AD_SDK.uploadAdInfo('request', param)
          GLOBAL_UTILS.global_data._APP.ylh_sdk.onYlhReady(() => {
            const params = {
              count: 1,
              appId: advIdsConfig.product_id,
              placementId: param.id,
              recommendation: 0,
            }
            GLOBAL_UTILS.global_data._APP.ylh_sdk.loadFeedAd(params).then(res => {
              console.log(res, 'native-custom_ylh-----------success')
              if (res && res.length > 0) {
                const data = {
                  ...nativeAdvConfig,
                  ...param,
                  app_id: advIdsConfig.product_id,
                  ecpm: nativeAdvConfig.ecpm,
                  advDetail: res[0],
                  fun: callback
                }
                resolve(data)
              } else {
                param.result = `无广告-错误码获取失败`
                resolve(false)
              }
            }).catch(err => {
              console.log(err, 'native-custom_ylh-----------error')
              param.result = `无广告${err.code}`
              resolve(false)
            })
          })
        } else if (
          nativeAdvConfig.styleType &&
          nativeAdvConfig.styleType.indexOf('m') !== -1 &&
          pvc > 1105 &&
          AD.preloadAd !== undefined
        ) {
          param.ad_type = '原生模板'
          AD_SDK.uploadAdInfo('request', param)
          let adParams = {
            adUnitId: nativeAdvConfig.id,
            type: 'custom',
            adCount: 1,
          }
          console.log(adParams, 'native-custom_custom-----------adParams')
          AD.preloadAd({
            ...adParams,
            success: (res) => {
              console.log(nativeAdvConfig.id, '_', nativeAdvConfig.styleType, res, 'native-custom_custom-----------success')
              let advDetail = {}
              if (res && res.adList) {
                res.adList[0].current_status = nativeAdvConfig.current_status
                advDetail = res.adList[0]
              } else {
                advDetail = {
                  adId: new Date().getTime(),
                  current_status: nativeAdvConfig.current_status
                }
              }
              let data = {
                ...nativeAdvConfig,
                ...param,
                ecpm: nativeAdvConfig.ecpm,
                advDetail,
                fun: callback
              }
              resolve(data)
            },
            fail: (data, code) => {
              console.log(data, 'native-custom_custom-----------fail')
              param.result = AD_SDK.errMsgFormat('无广告', data)
              resolve(false)
            },
          })
        } else {
          // 原生自渲染区域
          if (AD.preloadAd !== undefined && ad_sdk_global.versionCode >= 11030201) {
            AD_SDK.uploadAdInfo('request', param)
            let adParams = {
              adUnitId: nativeAdvConfig.id,
              type: 'native',
              adCount: 1,
            }
            AD.preloadAd({
              ...adParams,
              success: (res) => {
                if (res && Array.isArray(res.adList) && res.adList.length > 0) {
                  const data = {
                    ...nativeAdvConfig,
                    ...param,
                    ecpm: nativeAdvConfig.ecpm,
                    advDetail: res.adList[0],
                    fun: callback
                  }
                  resolve(data)
                } else {
                  param.result = AD_SDK.errMsgFormat('无广告', res)
                  resolve(false)
                }
              },
              fail: (res, code) => {
                param.result = AD_SDK.errMsgFormat('无广告', res)
                resolve(false)
              },
            })
          }
        }
      }, Number(timeout))
    })
    // 清除请求超时任务
    if (preloadTimer) {
      clearTimeout(preloadTimer)
      preloadTimer = null
    }
    // 清除层级请求间隔任务
    if (intervalTimer) {
      clearTimeout(intervalTimer)
      intervalTimer = null
    }
    console.log(results, 'native-custom-----------results')
    if (results) {
      // 记录有广告层级，供前几层请求使用
      if (!isBidding) {
        advIdsConfig['advIds'].yetLayer = nativeAdvConfig.layer
      }
      adDataHandle(obj, results)
    } else {
      AD_SDK.uploadAdInfo('request', param)
      // 更新当前广告位请求失败次数
      const failNum = advIdsConfig.num_fail
      if (failNum > 0) {
        let nowItem = advIdsConfig[`${isBidding ? 'biddingIds' : 'advIds'}`].layers[nativeAdvConfig.layer].adsArr[nativeAdvConfig.curIndex]
        nowItem.failNum = nowItem.failNum + 1 >= failNum ? true : false
      }
      obj.preDeleteStatus = {
        stauts: false,
        layer: 0
      }
      await getNewNativeAdv(obj, callback, false)
    }
  } else {
    LOG('AD', `广告ADSDK========>无可用广告位ID`)
    if (advIdsConfig && !isBidding) {
      advIdsConfig['advIds'].yetLayer = 0
    }
    callback && callback()
  }
}
/**
 * 广告返回数据处理
 * @param item  广告返回数据
 */
const adDataHandle = (obj, item) => {
  console.log(item, 'native-custom-----------item')
  let advDetail = item.advDetail, { sceneCode, adType, adTimes, isBidding } = obj
  let commonParams = {
    adType,
    adTimes,
    sceneCode,
    brand: ad_sdk_global.deviceInfo.brand,
    isBidding,
    result: '有广告',
  }
  item.adMethod = '2.0'
  item.title = advDetail.title
  item.desc = advDetail.desc
  if (item.styleType == 'renderer') {
    item.icon = advDetail.icon
    item.clickBtnTxt = advDetail.clickBtnTxt || '立即查看'
    item.materialUrl = AD_SDK.getMaterialUrlByAdData(
      advDetail
    )
    if (advDetail.appInfo) {
      advDetail.appInfo.appSize = advDetail.appInfo.appSize
        ? Number((advDetail.appInfo.appSize / 1024).toFixed(1))
        : '未知'
    }
    if (item.materialUrl.indexOf('.mp4') != -1) {
      item.poster = advDetail
        .imgUrlList[1]
        ? advDetail.imgUrlList[1]
        : ad_sdk_global.defaultAdImg
    }
    item.ad_type = item.poster
      ? '原生视频2.0'
      : '原生图片2.0'
    const interactionTypeM = {
      0: '无',
      1: '链接推广',
      2: '应用推广',
      3: '链接推广',
      4: '打开应用',
      5: '打开应用',
    }
    item.ad_style = interactionTypeM[advDetail.interactionType] || '无'
    advDetail.current_status = item.current_status
  } else if (item.styleType == 'ylh') {
    item.advDetail.adId = item.advDetail.id
    item.advDetail.pkgSizeBytes = item.advDetail.pkgSizeBytes ? Math.floor(item.advDetail.pkgSizeBytes / 1024 / 1024) : ''
    item.icon = item.advDetail.adLogo
    item.clickBtnTxt = item.advDetail.btnTxt || '立即查看'
    item.materialUrl = item.advDetail.img
    item.ad_type = item.advDetail.hasVideo
      ? '优量汇视频2.0'
      : '优量汇图片2.0'
    item.ad_style = item.advDetail.isApp ? '下载类' : '打开类'
  }
  fetch.fetch({
    url: item.materialUrl,
    method: 'get',
  })
  let result = Object.assign({}, item, commonParams);
  console.log(result, 'native-custom-----------adDataHandle')
  AD_SDK.uploadAdInfo('request', result)
  if (ad_sdk_global.showControlList.some(v => v.type == result.adTypes)) {
    result.wait = true
    ad_sdk_global.responseList.push(result)
    // // 按ecpm排序
    ad_sdk_global.responseList.sort((a, b) => b.ecpm - a.ecpm)
  }
  result.fun(result)
}
/**
 * 请求广告
 * @param obj.scenario 获取的广告场景
 * @param obj.sceneCode 获取的广告场景code
 * @param obj.adTimes 当前广告请求轮询次数
 * @param obj.adType 当前广告请求类型
 * @param obj.popName 当前弹窗名称
 * @param obj.popGroupName 当前广告弹窗组名称
 * @param obj.requestNum 当前广告请求第几个
 * @param obj.success 获取广告成功回调
 * @param obj.fail 获取广告失败回调
 */
async function getManuAdv(obj, reloadCount = 0) {
  LOG('AD', 'getManuAdv============>', obj)
  if (ad_sdk_global.initStatus != 2) {
    if (reloadCount < 2) {
      LOG(
        'AD',
        `广告ADSDK========>初始化未完，广告重新拿取次数${reloadCount + 1}`
      )
      let timeOut = setTimeout(() => {
        getManuAdv(obj, reloadCount + 1)
        clearTimeout(timeOut)
        timeOut = null
      }, 50)
    } else {
      obj && obj.fail && obj.fail('广告sdk还没初始化完')
    }
    return
  }
  if (!obj.sceneCode) {
    obj && obj.fail && obj.fail('场景code为空')
    return
  }

  obj.scenario = obj && obj.scenario ? obj.scenario : '未知'
  obj.adTimes = obj && obj.adTimes ? obj.adTimes : 0
  if (obj.scenario == '厂商广告联盟') {
    switch (obj.adType) {
      case 1: // 底通原生
        getBannerNativeAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
      case 2:
        getBannerNativeAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
      case 3:
        getBqtAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
    }
  } else {
    switch (obj.adType) {
      case 1: //原生
        getNativeAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
      case 2:
        getNativeAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
      case 3:
        getBqtAd(obj, (adData) => {
          if (adData) {
            obj && obj.success && obj.success(adData)
          } else {
            obj && obj.fail && obj.fail(obj.adType)
          }
        })
        break
    }
  }
}

/**
 * 获取原生广告
 * @param {Object} param
 * @param {Function} callBack
 */
function getNativeAd(param, callBack) {
  if (ad_sdk_global.deviceInfo.platformVersionCode > 1073) {
    getNewNativeAdv(param, (result) => {
      if (result) {
        callBack && callBack(result)
      } else {
        callBack && callBack('')
      }
    })
  }
}
export { initNativeSdk, initBqtSdk, getManuAdv }
